package com.blog.search;


import com.blog.domain.Favorites;
import com.blog.itpub.HtmlUtils;
import com.blog.itpub.SimpleCrawler;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

public class UpdateIndexService {

	public static String indexDir = null;
	private static IKAnalyzer analyzer = new IKAnalyzer(true);
	private static Directory directory = null;
	private static IndexWriter writer = null;

	public static void setIndexDir(String path) throws IOException {
		indexDir = path;
		File file = new File(indexDir);
		if( !file.exists() ){
			file.mkdirs();
		}
		directory = new NIOFSDirectory(file);

	}

	private static IndexWriterConfig getConfig(){
		IndexWriterConfig config = null;
		config = new IndexWriterConfig(Version.LUCENE_34,analyzer);
		config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
		return config;
	}

	public static void add(Favorites f) throws IOException {
		try{
			writer = new IndexWriter(directory,getConfig());
			Pair<Integer, String> html = null;
			try{
				html = SimpleCrawler.get(f.getFlink(), Charset.forName("UTF-8"));
			}catch (IOException e){
				e.printStackTrace();
			}
			String title = f.getFname();
			String bodyText = "";
			if( html != null && html.getLeft() == 200 && html.getRight() != null){
				bodyText = HtmlUtils.bodyText(html.getRight());
				title = HtmlUtils.title(html.getRight());
			}

			Document doc = new Document();
			doc.add(new Field("content", bodyText, Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("name", f.getFname(), Field.Store.YES, Field.Index.ANALYZED));
			doc.add(new Field("url", f.getFlink(), Field.Store.YES, Field.Index.NOT_ANALYZED));
			doc.add(new Field("ops",String.valueOf(f.getOps()), Field.Store.YES, Field.Index.NOT_ANALYZED));
			writer.addDocument(doc);
			writer.optimize();

		}finally {
			if(writer != null){
				writer.close();
				SearchService.needReopen();
				writer = null;
			}
		}
	}

	public static void delete(Favorites f) throws IOException {
		writer = new IndexWriter(directory,getConfig());
		writer.deleteDocuments(new Term("url", f.getFlink()));
		writer.close();
		SearchService.needReopen();
	}

	public static void update(Favorites f) throws IOException {
		delete(f);
		add(f);
		SearchService.needReopen();
	}

}
